//
//  PlayerViewController.swift
//  Gamers
//
//  Created by 虚空之翼 on 15/7/27.
//  Copyright (c) 2015年 Freedom. All rights reserved.
//

import UIKit
import youtube_ios_player_helper
import PagingMenuController
import Social
import Bolts
import RealmSwift
import MBProgressHUD
import DBAlertController
import MJRefresh

class PlayerViewController: UIViewController {

    var videoData: Video!
    var channelData: Channel!
    var videoRelateData = [Video]()
    var commentData = [YTVComment]()
    var pageToken = ""          //分页偏移量，默认为上次最后一个视频ID的nextpagetoken
    var maxResults = 20         //每页评论数量
    
    var isNoMoreData: Bool = false  //解决控件不能自己判断BUG
    var isLoaded = 0
    
    let userDefaults = NSUserDefaults.standardUserDefaults()    //用户全局登入信息
    // 导航条默认隐藏
    var isflage = true
    var isPlay = 0
    var isMoveView = false

    @IBOutlet weak var containerView: UIView!
    @IBOutlet weak var playerView: YTPlayerView!

    // 键盘属性,输入框
    var keyboardMoveStatus: Bool = false
    var keyboardHeight: CGFloat = 0
    var chatToolViewMoveStatus: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 设置顶部导航条样式，透明，另外一种方式，先备注预留
//        self.navigationItem.title = videoData.videoTitle
//        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont(name: "Heiti SC", size: 17.0)!]
        
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(),forBarMetrics: UIBarMetrics.Default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        self.navigationController?.navigationBar.translucent = true
        
        // 加载视频播放
        let playerVars = ["playsinline": 1, "showinfo": 1, "origin": "http://www.gamers.tm"]
        playerView.loadWithVideoId(videoData.videoId, playerVars: playerVars)
        
        // 添加加载新视频数据的监听器
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadPlayerView:", name: "reloadPlayerViewNotification", object: nil)
        // 播放全屏的监听事件
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "endFullScreen", name: UIWindowDidBecomeHiddenNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "begainFullScreen", name: UIWindowDidBecomeVisibleNotification, object: nil)
        // 评论界面上移事件
        //NSNotificationCenter.defaultCenter().addObserver(self, selector: "moveUpView", name: "moveUpViewNotification", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "MBProgressHUDHide", name: "MBProgressHUDHideNotification", object: nil)
        
        // 标签切换页面
        let VideoInfoVC = self.storyboard?.instantiateViewControllerWithIdentifier("VideoInfoVC") as! VideoInfoController
        VideoInfoVC.title = NSLocalizedString("Description", comment: "詳情")
        VideoInfoVC.videoData = videoData
        let VideoRelateVC = self.storyboard?.instantiateViewControllerWithIdentifier("VideoRelateVC") as! VideoRelateController
        VideoRelateVC.title = NSLocalizedString("Videos", comment: "相關影片")
        VideoRelateVC.videoData = videoData
        let VideoCommentVC = self.storyboard?.instantiateViewControllerWithIdentifier("VideoCommentVC") as! VideoCommentController
        VideoCommentVC.title = NSLocalizedString("Comments", comment: "留言")
        VideoCommentVC.videoData = videoData
        let viewControllers = [VideoInfoVC, VideoRelateVC, VideoCommentVC]

        let options = PagingMenuOptions()
        options.menuHeight = 32
        options.menuDisplayMode = PagingMenuOptions.MenuDisplayMode.SegmentedControl
        options.selectedTextColor = UIColor.orangeColor()
        options.menuItemMode = PagingMenuOptions.MenuItemMode.Underline(height: 2, color: UIColor.orangeColor(), horizontalPadding: 0, verticalPadding: 0)
        //options.textColor = UIColor.blackColor()
        options.defaultPage = 2
        
        let pagingMenuController = self.childViewControllers.first as! PagingMenuController
        pagingMenuController.delegate = self
        pagingMenuController.setup(viewControllers: viewControllers, options: options)
        
        // 保存数据
        VideoBL.sharedSingleton.setPlayHistory(videoData)
        playerView.delegate = self

        

        //let hub = MBProgressHUD.showHUDAddedTo(self.navigationController!.view, animated: true)
        //hub.labelText = NSLocalizedString("Loading...", comment: "加載中...")

        //隐藏后退键
        self.navigationItem.hidesBackButton = true
        
    }
    func MBProgressHUDHide() {
        //print(self.isPlay)
//        self.isPlay += 1
//        if self.isPlay >= 2 {
//            playerView.playVideo()
//
//            self.navigationItem.hidesBackButton = false
//            MBProgressHUD.hideHUDForView(navigationController!.view, animated: true)
//            self.isPlay = 0
//        }
        self.navigationItem.hidesBackButton = false
        MBProgressHUD.hideHUDForView(navigationController!.view, animated: true)
    }
    
    // 重新加载视频
    func reloadPlayerView(notification: NSNotification) {
        let userInfo = notification.userInfo!
        let newVideoData = userInfo["data"] as! Video
        
        let playerVars = ["playsinline": 1, "showinfo": 1, "origin": "http://www.gamers.tm"]
        playerView.loadWithVideoId(newVideoData.videoId, playerVars: playerVars)
        
        //videoViews.text = String(newVideoData.views) + " 次"

        // 保存数据
        VideoBL.sharedSingleton.setPlayHistory(newVideoData)
    }

    // 隐藏系统状态栏
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return UIStatusBarStyle.Default
    }
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
    
    // 横屏切换
    func begainFullScreen() {
        let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appDelegate.allowRotation = true
    }
    
    func endFullScreen() {
        let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appDelegate.allowRotation = false

        //强制归正：
        let sharedApplication: UIApplication = UIApplication.sharedApplication()
        sharedApplication.setStatusBarOrientation(UIInterfaceOrientation.Portrait, animated: true)
        let mvc: UIViewController = UIViewController()
        self.presentViewController(mvc, animated: true, completion: nil)
        self.dismissViewControllerAnimated(true, completion: nil)

    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(),forBarMetrics: UIBarMetrics.Default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        self.navigationController?.navigationBar.translucent = true
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

// MARK: - 标签导航代理
extension PlayerViewController: PagingMenuControllerDelegate {
    func willMoveToMenuPage(page: Int) {
        //println(page)
        //println("触发willMoveToMenuPage事件")
    }
    func didMoveToMenuPage(page: Int) {
        if page != 2 {
            //NSNotificationCenter.defaultCenter().postNotificationName("handleTapGestureNotification", object: nil, userInfo: nil)
        }
    }
}
// MARK: - youtube播放代理
extension PlayerViewController: YTPlayerViewDelegate {
    // 加载完成立即播放
    func playerViewDidBecomeReady(playerView: YTPlayerView!) {
        //NSNotificationCenter.defaultCenter().postNotificationName("MBProgressHUDHideNotification", object: nil, userInfo: nil)
        playerView.playVideo()
    }
    func playerView(playerView: YTPlayerView!, receivedError error: YTPlayerError) {
        //NSNotificationCenter.defaultCenter().postNotificationName("MBProgressHUDHideNotification", object: nil, userInfo: nil)
    }
}
// MARK: 网络Web代理
extension PlayerViewController: UIWebViewDelegate {
    func webViewDidFinishLoad(webView: UIWebView) {
        NSUserDefaults.standardUserDefaults().setInteger(0, forKey: "WebKitCacheModelPreferenceKey")
        NSUserDefaults.standardUserDefaults().setBool(false, forKey: "WebKitDiskImageCacheEnabled")
        NSUserDefaults.standardUserDefaults().setBool(false, forKey: "WebKitOfflineWebApplicationCacheEnabled")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
}

